var express = require("express");
const { path } = require("../../app");
var router = express.Router();

//导入shortid
const shortid = require("shortid");
const { default: mongoose } = require("mongoose");

//导入moment
const moment = require("moment");

//导入model
const accountmodel = require("../../models/accountmodel");

/* GET home page. */
router.get("/", function (req, res, next) {
  res.render("index", { title: "Express" });
});

//记账本列表
router.get("/account", function (req, res, next) {
  let accounts = accountmodel
    .find()
    .sort({ time: 1 })
    .then((result) => {
      res.json({
        code: "0000",
        msg: "读取成功",
        data: result,
      });
    })
    .catch((err) => {
      res.json({
        code: "1001",
        msg: "读取失败",
        data: null,
      });
    });
});

//添加记录
router.post("/account", function (req, res, next) {
  let data = req.body;
  accountmodel
    .create({
      ...data, //ES6语法
      time: moment(data.time).toDate(),
    })
    .then((result) => {
      res.json({
        code: "0000",
        msg: "保存成功",
        data: result,
      });
    })
    .catch((err) => {
      res.json({
        code: "1002",
        msg: "保存失败",
        data: null,
      });
    });
});

//删除记录
router.delete("/account/:_id", (req, res) => {
  //获取 params 的 id 参数
  let _id = req.params._id;
  //删除
  accountmodel
    .deleteOne({ _id: _id })
    .then((result) => {
      res.json({
        code: "0000",
        msg: "删除成功",
        data: result,
      });
    })
    .catch((err) => {
      res.json({
        code: "1003",
        msg: "删除失败",
        data: null,
      });
    });
});

//获取单个记录
router.get("/account/:id", function (req, res, next) {
  let { id } = req.params;
  let accounts = accountmodel
    .findById(id)
    .then((result) => {
      res.json({
        code: "0000",
        msg: "读取成功",
        data: result,
      });
    })
    .catch((err) => {
      res.json({
        code: "1001",
        msg: "读取失败",
        data: null,
      });
    });
});

//更新单个账单信息
router.patch("/account/:id", function (req, res, next) {
  let { id } = req.params;
  let accounts = accountmodel
    .updateOne({ _id: id }, req.body)
    .then((result) => {
      res.json({
        code: "0000",
        msg: "更新成功",
        data: result,
      });
    })
    .catch((err) => {
      res.json({
        code: "1005",
        msg: "更新失败",
        data: null,
      });
    });
});

module.exports = router;
